const request = require('../../utils/request');

Page({
  data: {
    nickname: '',
    saving: false,
    avatarUrl: '',
    role: '',
    phone: '',
    // 通用/下单者字段
    realName: '',
    schoolName: '',
    dormitory: '',
    contactWechat: '',
    defaultPickupSite: '',
    orderNote: '',
    // 代拿员字段
    studentId: '',
    serviceCampusArea: '',
    serviceTimeRange: '',
    serviceDesc: ''
  },

  onLoad() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }
    this.loadProfile(userId);
  },

  async loadProfile(userId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: request.buildUrl(`/api/users/profile/${userId}`),
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: (r) => resolve(r.data),
          fail: reject
        });
      });

      if (res.success && res.data) {
        const root = res.data || {};
        const user = root.user || root;
        const orderUser = root.order_user || {};
        const courierUser = root.courier_user || {};

        const avatarPath = user.avatar_url || user.avatar || '';
        this.setData({
          role: root.role || user.role || getApp().globalData.userRole || '',
          nickname: user.nickname || '',
          avatarUrl: avatarPath ? request.buildUrl(avatarPath) : '',
          phone: user.phone || '',
          realName: orderUser.real_name || courierUser.real_name || '',
          schoolName: orderUser.school_name || courierUser.school_name || '',
          dormitory: orderUser.dormitory || '',
          contactWechat: orderUser.contact_wechat || courierUser.contact_wechat || '',
          defaultPickupSite: orderUser.default_pickup_site || '',
          orderNote: orderUser.note || '',
          studentId: courierUser.student_id || '',
          serviceCampusArea: courierUser.service_campus_area || '',
          serviceTimeRange: courierUser.service_time_range || '',
          serviceDesc: courierUser.service_desc || ''
        });
      }
    } catch (e) {
      console.error('加载个人资料失败:', e);
    }
  },

  onInputChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    if (!field) return;
    this.setData({ [field]: value });
  },

  onChangeAvatar() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const filePath = res.tempFilePaths[0];
        if (!filePath) return;

        wx.showLoading({ title: '正在上传...', mask: true });

        const uploadUrl = request.buildUrl(`/api/upload/avatar?userId=${userId}`);

        wx.uploadFile({
          url: uploadUrl,
          filePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token') || ''}`
          },
          success: (resp) => {
            try {
              const data = JSON.parse(resp.data || '{}');
              if (data.success && data.data && data.data.url) {
                const avatarPath = data.data.url; // 相对路径，如 /uploads/avatars/xxx.jpg
                const fullUrl = request.buildUrl(avatarPath);
                this.setData({ avatarUrl: fullUrl });

                // 将头像路径保存到用户资料中，便于“我的主页”等页面读取
                wx.request({
                  url: request.buildUrl(`/api/users/${userId}`),
                  method: 'PUT',
                  data: {
                    avatar_url: avatarPath
                  },
                  header: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${wx.getStorageSync('token') || ''}`
                  },
                  complete: () => {
                    // 不论成功失败，前端头像已更新；失败时可在控制台查看
                    wx.showToast({ title: '头像已更新', icon: 'success' });
                  }
                });
              } else {
                wx.showToast({ title: data.message || '上传失败', icon: 'none' });
              }
            } catch (e) {
              wx.showToast({ title: '上传响应解析失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '上传失败，请稍后再试', icon: 'none' });
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      }
    });
  },

  goEditNickname() {
    wx.navigateTo({ url: '/pages/profile/editNickname' });
  },

  goChangePassword() {
    wx.navigateTo({ url: '/pages/profile/changePassword' });
  },

  onSave() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    // 简单必填校验
    if (!this.data.nickname) {
      wx.showToast({ title: '请先设置昵称', icon: 'none' });
      return;
    }

    const payload = {
      nickname: this.data.nickname,
      real_name: this.data.realName,
      school_name: this.data.schoolName,
      dormitory: this.data.dormitory,
      contact_wechat: this.data.contactWechat,
      default_pickup_site: this.data.defaultPickupSite,
      note: this.data.orderNote,
      student_id: this.data.studentId,
      service_campus_area: this.data.serviceCampusArea,
      service_time_range: this.data.serviceTimeRange,
      service_desc: this.data.serviceDesc
    };

    this.setData({ saving: true });

    wx.request({
      url: request.buildUrl(`/api/users/profile/${userId}`),
      method: 'PUT',
      data: payload,
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token') || ''}`
      },
      success: (res) => {
        if (res.data && res.data.success !== false) {
          wx.showToast({ title: '保存成功', icon: 'success' });
          setTimeout(() => {
            wx.navigateBack({ delta: 1 });
          }, 500);
        } else {
          wx.showToast({ title: (res.data && res.data.message) || '保存失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '保存失败，请稍后再试', icon: 'none' });
      },
      complete: () => {
        this.setData({ saving: false });
      }
    });
  }
});
